package cn.common.component.controller;

import cn.common.component.entity.Qrcodewithproduct;
import cn.common.component.repository.QrcodeproductRepository;
import cn.common.component.utils.ComponentUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.boot.autoconfigure.klock.model.LockType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Controller
public class RunController {

    public static final Logger log = LoggerFactory.getLogger(RunController.class);

    @Autowired
    private QrcodeproductRepository qrcodeproductRepository;

    private List<Qrcodewithproduct> qrcodewithproductList = new LinkedList<>();

    @GetMapping("runqrcode")
    @ResponseBody
    public String testproc(){

        qrcodewithproductList = qrcodeproductRepository.findAll();


        for (int i = 0; i < qrcodewithproductList.size(); i++) {
            try {
                Qrcodewithproduct temp = qrcodewithproductList.get(i);
                String eptCode = temp.getEptcode();

                JSONObject jsondate = new JSONObject();


                Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsondate, Qrcodewithproduct.class);

                qrcodeproductRepository.save(qrcodewithproduct);
            } catch (Exception e) {
                System.out.println(e.toString());
                System.out.println("Error ===========================================");
            }

        }

/*        JSONObject jsonObject = ComponentUtils.sendHttpRequestByGet("https://qr.huggies.com.cn:8099/openapi/proj/codequery/query?codeType=1&code=02302659606372971645",
                "ehsure@2017",
                "8BiUk$.)tpJ8wt$Cs[p0Sjv+[*iF^p");

        System.out.println(jsonObject.toJSONString());

        Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsonObject, Qrcodewithproduct.class);*/


        return "success";
    }


    private JSONObject getQrcodeInfo(String codeType, String code) {
        JSONObject result = new JSONObject();

        JSONObject jsonObject = ComponentUtils.sendHttpRequestByGet("https://qr.huggies.com.cn:8099/openapi/proj/codequery/query?codeType=" + codeType +"&code=" + code,
                "ehsure@2017",
                "8BiUk$.)tpJ8wt$Cs[p0Sjv+[*iF^p");

        log.info(jsonObject.toJSONString());
        JSONObject jsondate = jsonObject.getJSONObject("data");

        return jsondate;
    }

    private List<Qrcodewithproduct> qrcodewithproductList1 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList2 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList3 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList4 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList5 = new LinkedList<>();


    private List<Qrcodewithproduct> qrcodewithproductList6 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList7 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList8 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList9 = new LinkedList<>();
    private List<Qrcodewithproduct> qrcodewithproductList10 = new LinkedList<>();


    @GetMapping("runqrcodebbs")
    @ResponseBody
    public synchronized String testproc2() {

        qrcodewithproductList1 = qrcodeproductRepository.findAllByStatusIsNullAndParam02IsNullAndFlatEquals(1);
        qrcodewithproductList2 = qrcodeproductRepository.findAllByStatusIsNullAndParam02IsNullAndFlatEquals(2);
        qrcodewithproductList3 = qrcodeproductRepository.findAllByStatusIsNullAndParam02IsNullAndFlatEquals(3);
        qrcodewithproductList4 = qrcodeproductRepository.findAllByStatusIsNullAndParam02IsNullAndFlatEquals(4);
        qrcodewithproductList5 = qrcodeproductRepository.findAllByStatusIsNullAndParam02IsNullAndFlatEquals(5);

        log.info(" @@ "+ qrcodewithproductList1.size());
        log.info(" @@ "+ qrcodewithproductList2.size());
        log.info(" @@ "+ qrcodewithproductList3.size());
        log.info(" @@ "+ qrcodewithproductList4.size());
        log.info(" @@ "+ qrcodewithproductList5.size());


        Thread t1 = new Thread(()->{
            for (int i = 0; i < qrcodewithproductList1.size(); i++) {
                try {
                    Qrcodewithproduct temp = qrcodewithproductList1.get(i);
                    String code = temp.getCode();

                    JSONObject jsondate = getQrcodeInfo("2", code);

                    Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsondate, Qrcodewithproduct.class);

                    qrcodeproductRepository.save(qrcodewithproduct);

                    temp.setParam02("1");
                    qrcodeproductRepository.saveAndFlush(temp);
                } catch (Exception e) {
                    log.error(e.toString());
                    log.error("Error 111 ===========================================");
                }

            }
        });

        Thread t2 = new Thread(()->{
            for (int i = 0; i < qrcodewithproductList2.size(); i++) {
                try {
                    Qrcodewithproduct temp = qrcodewithproductList2.get(i);
                    String code = temp.getCode();

                    JSONObject jsondate = getQrcodeInfo("2", code);

                    Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsondate, Qrcodewithproduct.class);

                    qrcodeproductRepository.save(qrcodewithproduct);

                    temp.setParam02("1");
                    qrcodeproductRepository.saveAndFlush(temp);
                } catch (Exception e) {
                    log.error(e.toString());
                    log.error("Error 222 ===========================================");
                }

            }
        });

        Thread t3 = new Thread(()->{
            for (int i = 0; i < qrcodewithproductList3.size(); i++) {
                try {
                    Qrcodewithproduct temp = qrcodewithproductList3.get(i);
                    String code = temp.getCode();

                    JSONObject jsondate = getQrcodeInfo("2", code);

                    Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsondate, Qrcodewithproduct.class);

                    qrcodeproductRepository.save(qrcodewithproduct);

                    temp.setParam02("1");
                    qrcodeproductRepository.saveAndFlush(temp);
                } catch (Exception e) {
                    log.error(e.toString());
                    log.error("Error 333 ===========================================");
                }

            }
        });

        Thread t4 = new Thread(()->{
            for (int i = 0; i < qrcodewithproductList4.size(); i++) {
                try {
                    Qrcodewithproduct temp = qrcodewithproductList4.get(i);
                    String code = temp.getCode();

                    JSONObject jsondate = getQrcodeInfo("2", code);

                    Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsondate, Qrcodewithproduct.class);

                    qrcodeproductRepository.save(qrcodewithproduct);

                    temp.setParam02("1");
                    qrcodeproductRepository.saveAndFlush(temp);
                } catch (Exception e) {
                    log.error(e.toString());
                    log.error("Error 4444 ===========================================");
                }

            }
        });

        Thread t5 = new Thread(()->{
            for (int i = 0; i < qrcodewithproductList5.size(); i++) {
                try {
                    Qrcodewithproduct temp = qrcodewithproductList5.get(i);
                    String code = temp.getCode();

                    JSONObject jsondate = getQrcodeInfo("2", code);

                    Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsondate, Qrcodewithproduct.class);

                    qrcodeproductRepository.save(qrcodewithproduct);

                    temp.setParam02("1");
                    qrcodeproductRepository.saveAndFlush(temp);
                } catch (Exception e) {
                    log.error(e.toString());
                    log.error("Error 555 ===========================================");
                }

            }
        });

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

        return "success";
    }


    Integer cursorTemp = -1;
    JSONObject cursorBox = new JSONObject();

    /**
     * 并行获取包装信息
     * @param request
     * @param beginLi
     * @param endLi
     * @return
     */
    @GetMapping("runqrcodeParallbel")
    @ResponseBody
    public synchronized String parallelGetQrcode(HttpServletRequest request ,
                                                 @RequestParam(required = true) Integer beginLi , @RequestParam(required = true)Integer endLi ,
                                                 @RequestParam(required = true) Integer codeType) throws InterruptedException {
        cursorTemp = beginLi;
//        Integer endCursorTemp = endLi;

        for (  ; cursorTemp <= endLi; cursorTemp++) {
//            cursor = cursorTemp;
            cursorBox.put("cursor", cursorTemp);

            Thread tt = new Thread(()->{
                Integer cursort = (Integer)cursorBox.getInteger("cursor");
//                cursor ++ ;
                List<Qrcodewithproduct> qrcodewithproductListi = qrcodeproductRepository.findAllByStatusIsNullAndParam02IsNullAndFlatEquals(cursort);

                for (int j = 0; j < qrcodewithproductListi.size(); j++) {
                    try {
                        log.info("cursor = "+cursort);
//                        need to delete
//                        Thread.sleep(1000);

                        Qrcodewithproduct temp = qrcodewithproductListi.get(j);
                        String code = new String();

                        if (codeType == 2 ) {
                            code = temp.getCode();


                        } else if (codeType == 1) {
                            code = temp.getEptcode();
                        }

                        JSONObject jsondate = getQrcodeInfo(codeType.toString(), code);

                        Qrcodewithproduct qrcodewithproduct = JSON.toJavaObject(jsondate, Qrcodewithproduct.class);

                        qrcodewithproduct.setFlat(cursort);
                        qrcodeproductRepository.save(qrcodewithproduct);

                        temp.setParam02("1");
                        qrcodeproductRepository.saveAndFlush(temp);
                    } catch (Exception e) {
                        log.error(e.toString());
                        log.error("Error 555 ===========================================");
                    }

                }
            });

            tt.start();

            Thread.sleep(15000);


        }

        return "success";
    }














    @ResponseBody
    @RequestMapping("testss")
    public JSONObject tetete(HttpServletRequest request) {
        JSONObject result = new JSONObject();
        request.getSession().setAttribute("springsessoin","can you watch me ?");
        result.put("nowtime", new Date());
        return result;
    }

    @Klock(name = "testlock"  , lockType = LockType.Reentrant)
    @ResponseBody
    @RequestMapping("testlockm")
    public JSONObject testlockm(HttpServletRequest request) throws InterruptedException {
        JSONObject result = new JSONObject();
        request.getSession().setAttribute("springsessoin","can you watch me ?");
        for (int i = 0; i < 100; i++) {
            System.out.println("lock func 1m ### "+i);
            Thread.sleep(500);
        }
//        Thread.
        result.put("nowtime", new Date());
        return result;
    }

    @Klock(name = "testlock" , lockType = LockType.Reentrant)
    @ResponseBody
    @RequestMapping("testlockp")
    public JSONObject testlockp(HttpServletRequest request) throws InterruptedException {
        JSONObject result = new JSONObject();
        request.getSession().setAttribute("springsessoin","can you watch me ?");
        for (int i = 0; i < 100; i++) {
            System.out.println("lock func 2 $$$ "+i);
            Thread.sleep(500);
        }
        result.put("nowtime", new Date());
        return result;
    }
}


